package cc.cix.hq.org.service.impl;

import cc.cix.hq.common.core.entity.QueryRequest;
import cc.cix.hq.common.core.entity.constant.HqConstant;
import cc.cix.hq.common.core.entity.org.LoginLog;
import cc.cix.hq.common.core.utils.HqUtil;
import cc.cix.hq.common.core.utils.SortUtil;
import cc.cix.hq.org.mapper.LoginLogMapper;
import cc.cix.hq.org.service.ILoginLogService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @author cix
 */

@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements ILoginLogService {

    @Override
    public cc.cix.hq.common.core.entity.Page<LoginLog> listLoginLog(LoginLog loginLog, QueryRequest request) {
        QueryWrapper<LoginLog> qw = new QueryWrapper<>();
        SortUtil.handleWrapperSort(request, qw, request.getSortField(),
                HqConstant.ORDER_DESC, "loginTime", true);
        qw.lambda()
                .eq(StrUtil.isNotBlank(loginLog.getUsername()), LoginLog::getUsername, Optional.ofNullable(loginLog.getUsername()).map(String::toLowerCase));
        IPage<LoginLog> page = page(new Page<>(request.getPageNum(), request.getPageSize()), qw);
        return HqUtil.getPage(page);
    }

    @Override
    public void saveLoginLog(LoginLog loginLog) {
        loginLog.setLoginTime(LocalDateTime.now());
        String ip = HqUtil.getHttpServletRequestIpAddress();
        loginLog.setIp(ip);
        loginLog.setLocation(HqUtil.getHttpServletRequestIpAddress());
        save(loginLog);
    }

    @Override
    public List<LoginLog> listUserLastSevenLoginLogs(String username) {
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(username);

        QueryRequest request = new QueryRequest();
        request.setPageNum(1);
        // 近7次记录
        request.setPageSize(7);

        return listLoginLog(loginLog, request).getRows();
    }
}
